package leetcode101_xqzhao

// TODO 两数相加 【-】 链表

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil && l2 == nil {
		return nil
	}
	sign := 0 // 进位
	head := &ListNode{}
	p := head

	for l1 != nil || l2 != nil {
		p.Next = &ListNode{}
		p = p.Next
		v1, v2 := 0, 0
		if l1 != nil {
			v1 = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			v2 = l2.Val
			l2 = l2.Next
		}
		sum := v1 + v2 + sign
		sign = sum / 10
		p.Val = sum % 10
	}

	if sign != 0 {
		p.Next = &ListNode{Val: sign}
	}
	return head.Next
}
